package org.example.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NianBanBaoServer {
    public static void main(String[] args) {

        new ServerBootstrap()
                // 调整channel的容量
//                .option(ChannelOption.SO_RCVBUF,5)
                .channel(NioServerSocketChannel.class)
                .group(new NioEventLoopGroup())
                .childHandler(new ChannelInitializer<NioSocketChannel>(){
                    @Override
                    protected void initChannel(NioSocketChannel channel)   {
                        ChannelPipeline pipeline = channel.pipeline();
//                        pipeline.addLast(new FixedLengthFrameDecoder(16));
//                        pipeline.addLast(new LineBasedFrameDecoder(200));
//                        pipeline.addLast(new DelimiterBasedFrameDecoder(200, Unpooled.copiedBuffer("\\c".getBytes())));
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(200, 0, 1, 0, 0));
                        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                        pipeline.addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                super.channelActive(ctx);
                                log.info("链接建立了");
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                byte[] bytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(byteBuf.readerIndex(), bytes);
                                log.info("接收到的消息为：{}",new String(bytes));
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
